<template>
  <el-select
      style="width: 100%"
      v-model="modelVal"
      filterable
      v-loadmore="loadMore"
      remote
      :clearable="clearable"
      reserve-keyword
      @focus="focus"
      @blur="blur"
      @change="change"
      @visible-change="visibleChange"
      :remote-method="remoteMethod"
      :popper-append-to-body="false"
      :loading="selectLoading">
    <el-option
        v-for="(item, index) in option"
        :key="index"
        :label="item[propsObj.label]"
        :value="item[propsObj.value]"
        :disabled="item.disabled"
    ></el-option>
  </el-select>
</template>

<script>
import { deepClone } from '@/utils'
import { _deepClone } from '@/utils'

export default {
  name: 'index',
  props: {
    value: {
      type: [String, Number]
    },
    initData: {
      type: Array,
      default: () => []
    },
    propsObj: {
      type: Object,
      default: () => ({
        label: 'label',
        value: 'value'
      })
    },
    clearable: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectLoading: false,
      modelVal: '',
      option: [],
      blurReset: false,
      focusReset: false,
      isFirst: true,
      tempData: [],//初始数据暂存区
    }
  },
  watch: {
    value: {
      handler(val) {
        this.modelVal = val
      },
      immediate: true
    },
    initData: {
      handler(val) {
        if (val.length) {
          this.tempData = this.isFirst ? val : this.tempData
          this.isFirst = false
        }
        this.option = this.option.concat(val)
        this.selectLoading = false
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //模糊搜索
    remoteMethod(query) {
      this.resetOption()
      this.selectLoading = true
      this.resetOption()
      this.$emit('remoteSearch', query)
      // console.log('remote')
    },
    //下拉框关闭/显示事件
    visibleChange(isOpen) {
      this.resetOption()
      if (isOpen) this.$emit('openVisible')
      // console.log('isOpen')

    },
    //鼠标聚焦事件
    focus() {
      // console.log('focus')
      // this.resetOption()
      // this.$emit('focus')
      // this.option = _deepClone(this.tempData)
    },
    //失焦事件（失焦需清除模糊搜索条件）
    blur() {
      // console.log('blur')
      this.$emit('blurClear')
      setTimeout(() => {
        this.resetOption()
      }, 300)
    },
    //滚动加载
    loadMore() {
      // console.log('loadMore')
      this.$emit('loadMore')
    },
    change(value) {
      // console.log('change')
      this.$emit('input', value)
      let item = this.option.find(f => f.value === value)
      if (item) this.$emit('change', item)
    },
    //清空
    resetOption() {
      this.option = []
    }
  }
}
</script>

<style scoped>

</style>